package com.zhihaoliang.coroutine.buss.flow.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/27 11:25
 * @des Launching flow
 */
object FlowLaunch {

    fun onCollect(mainScope: CoroutineScope) = mainScope.launch {
        events()
            .onEach { event -> log("Collect Event: $event") }
            .collect() // <--- Collecting the flow waits
        log("Collect Done")
    }

    private fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(100) }

    fun onLaunchIn(mainScope: CoroutineScope) = mainScope.launch {
        events()
            .onEach { event -> log("LaunchIn Event: $event") }
            .launchIn(mainScope) // <--- Collecting the flow waits
        log("LaunchIn Done")
    }
}